package com.apes.fn.tms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.tms.model.*;
import com.apes.fn.tms.repository.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.stock.model.PhyDepot;
import com.apes.scm.masterdata.stock.repository.PhyDepotRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.PickItem;
import com.apes.scm.stock.transfer.repository.PickRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("carInformationService")
public class CarInformationService extends DomainService {
    @Autowired
    CarInformationRepository carInformationRepository;
    @Autowired
    WaybillRepository waybillRepository;
    @Autowired
    ChauffeurRepository chauffeurRepository;
    @Autowired
    CarDetailsRepository carDetailsRepository;
    @Autowired
    WaybillCargoDetailsRepository waybillCargoDetailsRepository;
    @Autowired
    PhyDepotRepository phyDepotRepository;
    @Autowired
    PickRepository pickRepository;
    @Autowired
    WaybillPlanningPlanRepository waybillPlanningPlanRepository;
    @Autowired
    WaybillPlanningLogRepository waybillPlanningLogRepository;
    @Autowired
    private PiManager piManager;
    @Autowired
    WaybillService waybillService;

    /**
     * 查询所有该司机待装车的派车单
     * 当参数里有门店信息时单查该门店运单
     * @param request
     * @return
     */
    public List findAllByChauffeur(SimpleRequest request){
        Map m = request.getMap();
        String phone = (String) m.get("phone");
        String phyDepotId = (String) m.get("phyDepotId");
        Chauffeur chauffeur = chauffeurRepository.findByMobileNumber(phone);
        List<Map> cacheList = new ArrayList();
        // 查询所有已指派给该司机的派车单
        List<CarInformation> carInformationList = carInformationRepository.findAllByChauffeurIdAndStatus(chauffeur,"assigned");
        carInformationList.forEach(carInformation -> {
            // 查询派车单下 待装车的线路规划的运单列表
            List<WaybillPlanningPlan> planningPlanList = waybillPlanningPlanRepository.findByCarInformationIdAndStatus(carInformation,"loading");
            List<Waybill> waybillList = planningPlanList.stream().map(WaybillPlanningPlan::getWaybillId).collect(Collectors.toList());
            //            List<CarDetails> carDetailsList = carDetailsRepository.findAllByCarInformationId(carInformation);
//            List<Waybill> waybillList = carDetailsList.stream().map(CarDetails::getWaybillId).collect(Collectors.toList());
//            List<Waybill> waybillList2 = new ArrayList<>();
//            waybillList.forEach(waybill -> {
//                List<WaybillPlanningPlan> planningPlans = waybillPlanningPlanRepository.findByWaybillIdAndStatus(waybill,"loading");
//                // 只有一个正在待装车的线路规划
//                waybillList2.addAll(planningPlans.stream().map(WaybillPlanningPlan::getWaybillId).collect(Collectors.toList()));
//            });

//            List<Waybill> waybillList = waybillRepository.findAllByCarInfomationAndStausAndASC(carInformation.getId(),"loading");
            List<PhyDepot> shippingAddressList = planningPlanList.stream().map(WaybillPlanningPlan::getShippingAddress).distinct().collect(Collectors.toList());
            if (phyDepotId!=null && !phyDepotId.isEmpty()){
                waybillList = planningPlanList.stream().filter(w -> w.getShippingAddress().getId().equals(phyDepotId)).map(WaybillPlanningPlan::getWaybillId).collect(Collectors.toList());
//                waybillList = waybillList2.stream().filter(w -> w.getShippingAddress().getId().equals(phyDepotId)).collect(Collectors.toList());
            }
            List<Map> maps = new ArrayList<>();

            waybillList.forEach(waybill -> {
                List<WaybillPlanningPlan> waybillPlanningPlanList = waybillPlanningPlanRepository.findByWaybillId(waybill);
                Optional<WaybillPlanningPlan> waybillPlanningPlan = waybillPlanningPlanList.stream().filter(w ->w.getStatus().equals("loading")).min(Comparator.comparing(WaybillPlanningPlan::getExecutionNumber));
                WaybillPlanningPlan plan = waybillPlanningPlan.get();
                Map map = MapUtil.mapper(
                        "id",waybill.getId(),
                        "sourceBusinessType",waybill.getSourceBusinessType(),
                        "sourceBusinessKey",waybill.getSourceBusinessKey(),
                        "transportStatus",waybill.getTransportStatus(),
                        "carInformationId",carInformation,
                        "deliveryAddress",plan.getDeliveryAddress(),
                        "waybillPlanningPlan",plan,
                        "shippingAddress",plan.getShippingAddress()
                );
                map.put("transit",false);
                if ( waybillPlanningPlanList.size()>1){
                    map.put("transit",true);
                }
                maps.add(map);
            });
            if(!maps.isEmpty()){
                cacheList.add(MapUtil.mapper(
                        "carInformationId", carInformation.getId(),
                        "PhyDepotList", shippingAddressList,
                        "waybillList", maps,
                        "type","装货确认"
                ));
            }

        });
        return cacheList;
    }



    /**
     * 查询运单详情
     * @param request
     * @return
     */
    public Map findAllByWaybill(SimpleRequest request){
        Map m = request.getMap();
        String waybillId = (String) m.get("waybillId");
        WaybillPlanningPlan waybillPlanningPlan = new WaybillPlanningPlan();
//        request.getO("waybillPlanningPlan",WaybillPlanningPlan.class);
        Waybill waybill = waybillRepository.findOne(waybillId);
//        CarInformation carInformation = carInformationRepository.findOneByWaybill(waybill,"assigned");
        WaybillPlanningPlan waybillPlanningPlan1 = waybillPlanningPlanRepository.findByWaybillId(waybill).stream().filter(plan -> plan.getStatus().equals("loading")||plan.getStatus().equals("inTransit")
                ||plan.getStatus().equals("arrived")).min(Comparator.comparing(WaybillPlanningPlan::getExecutionNumber)).orElse(new WaybillPlanningPlan());
        CarInformation carInformation = waybillPlanningPlan1.getCarInformationId();
        List<WaybillCargoDetails> waybillCargoDetailsList = waybillCargoDetailsRepository.findAllByWaybillId(waybill);
        Map map = new HashMap();
        Map map1 = MapUtil.mapper(
                "id",waybill.getId(),
                "sourceBusinessType",waybill.getSourceBusinessType(),
                "sourceBusinessKey",waybill.getSourceBusinessKey(),
                "transportStatus",waybill.getTransportStatus(),
                "carInformationId",carInformation==null?"":carInformation,
                "vehicle",carInformation==null?"":carInformation.getVehicleId(),
                "deliveryAddress",waybill.getDeliveryAddress(),
                "shippingAddress",waybill.getShippingAddress(),
                "waybillPlanningPlan",waybillPlanningPlan,
                "shippingAddressPhone",waybill.getShippingAddress().getPhone()
        );
        map.put("waybill",map1);
        map.put("createDate",carInformation==null?"":carInformation.getCreateDate());
        map.put("waybillCargoDetailsList",waybillCargoDetailsList);
        // 如果运单已经被指派 取线路规划列表里最后一条线路的预计到达时间
        if (waybill.getTransportStatus().equals("inTransit") || waybill.getTransportStatus().equals("received")){
            List<WaybillPlanningPlan> waybillPlanningPlanList = waybillPlanningPlanRepository.findByWaybillId(waybill);
            Optional<WaybillPlanningPlan>  waybillPlanning = waybillPlanningPlanList.stream().max(Comparator.comparing(WaybillPlanningPlan::getExecutionNumber));
            map.put("arrivalTime",waybillPlanning.orElse(new WaybillPlanningPlan()).getArrivalTime());
        }
        return map;
    }

    /**
     * 查询已装货完成未签收的运单
     * 如果线路规划是有中转的不是最后执行顺序的线路不能签收
     * 只能中转收件
     * @param request
     * @return
     */
    public List findAllByStatus(SimpleRequest request){
        Map m = request.getMap();
        String phone = (String) m.get("phone");
        String phyDepotId = (String) m.get("phyDepotId");
        Chauffeur chauffeur = chauffeurRepository.findByMobileNumber(phone);
        List<Map> cacheList = new ArrayList();
        // 查询所有该司机已指派的派车单
        List<CarInformation> carInformationList = carInformationRepository.findAllByChauffeurIdAndStatus(chauffeur,"assigned");
        carInformationList.forEach(carInformation -> {
            // 此次派车单 所有运输中的 线路规划
            List<WaybillPlanningPlan> planningPlanList = waybillPlanningPlanRepository.findByCarInformationIdAndStatus(carInformation,"inTransit");
            List<Waybill> waybillList = planningPlanList.stream().map(WaybillPlanningPlan::getWaybillId).collect(Collectors.toList());
            // 此次派车单 所有 已装货 未签收的运单
//            List<Waybill> waybillList = waybillRepository.findAllByCarInfomationAndStausAndASC(carInformation.getId(),"inTransit");
            List<PhyDepot> shippingAddressList = planningPlanList.stream().map(WaybillPlanningPlan::getShippingAddress).distinct().collect(Collectors.toList());
            if (phyDepotId!=null && !phyDepotId.isEmpty()){
                waybillList = planningPlanList.stream().filter(w -> w.getShippingAddress().getId().equals(phyDepotId)).map(WaybillPlanningPlan::getWaybillId).collect(Collectors.toList());
//                waybillList = waybillList2.stream().filter(w -> w.getShippingAddress().getId().equals(phyDepotId)).collect(Collectors.toList());
            }
            List<Map> maps = new ArrayList<>();
            waybillList.forEach(waybill -> {
                List<WaybillPlanningPlan> waybillPlanningPlanList = waybillPlanningPlanRepository.findByWaybillId(waybill);
                // 运单线路规划最后执行的线路
                WaybillPlanningPlan waybillPlanningPlan = waybillPlanningPlanList.stream().max(Comparator.comparing(WaybillPlanningPlan::getExecutionNumber)).get();
                // 已经在运输中但是还未签收的运单的线路规划
                WaybillPlanningPlan plan = waybillPlanningPlanList.stream().filter(w ->w.getStatus().equals("inTransit")).min(Comparator.comparing(WaybillPlanningPlan::getExecutionNumber)).get();;
                // 如果此次执行的线路规划不是最后执行的线路 不能写到签收列表
                if (waybillPlanningPlan == plan){
                    Map map = MapUtil.mapper(
                            "id",waybill.getId(),
                            "sourceBusinessType",waybill.getSourceBusinessType(),
                            "sourceBusinessKey",waybill.getSourceBusinessKey(),
                            "transportStatus",waybill.getTransportStatus(),
                            "deliveryAddress",plan.getDeliveryAddress(),
                            "waybillPlanningPlan",plan,
                            "shippingAddress",plan.getShippingAddress()
                    );
                    map.put("transit",false);
                    if ( waybillPlanningPlanList.size()>1){
                        map.put("transit",true);
                    }
                    maps.add(map);
                }

            });
            if (!maps.isEmpty()){
                cacheList.add(MapUtil.mapper(
                        "carInformationId", carInformation.getId(),
                        "PhyDepotList", shippingAddressList,
                        "waybillList", maps,
                        "type","签收确认"
                ));
            }

        });
        return cacheList;
    }



    /**
     * 查询已签收的运单
     * @param request
     * @return
     */
    public List findAllByChauffeurAndStatus(SimpleRequest request){
        Map m = request.getMap();
        String phone = (String) m.get("phone");
        String phyDepotId = (String) m.get("phyDepotId");
        Chauffeur chauffeur = chauffeurRepository.findByMobileNumber(phone);
//        Chauffeur chauffeur = request.getO(Chauffeur.class);
        List<Map> cacheList = new ArrayList();
        // 查询所有该司机待装车的派车单
        List<CarInformation> carInformationList = carInformationRepository.findAllByChauffeurIdAndStatus(chauffeur,"assigned");
        carInformationList.forEach(carInformation -> {
            // 此次派车单 所有运单 经过的仓库
            List<CarDetails> carDetailsList = carDetailsRepository.findAllByCarInformationId(carInformation);
            // 此次派车单 所有 已装货 未签收的运单
            List<Waybill> waybillList = waybillRepository.findAllByCarInfomationAndStausAndASC(carInformation.getId(),"received");
            if (phyDepotId!=null && !phyDepotId.isEmpty()){
                waybillList = waybillList.stream().filter(w -> w.getShippingAddress().getId().equals(phyDepotId)).collect(Collectors.toList());
            }
            List<PhyDepot> shippingAddressList = waybillList.stream().map(Waybill::getShippingAddress).collect(Collectors.toList());
            List<Map> maps = new ArrayList<>();

            waybillList.forEach(waybill -> {
                Map map = MapUtil.mapper(
                        "id",waybill.getId(),
                        "sourceBusinessType",waybill.getSourceBusinessType(),
                        "sourceBusinessKey",waybill.getSourceBusinessKey(),
                        "transportStatus",waybill.getTransportStatus(),
                        "deliveryAddress",waybill.getDeliveryAddress(),
                        "shippingAddress",waybill.getShippingAddress()
                );
                maps.add(map);
            });
            cacheList.add(MapUtil.mapper(
                    "carInformationId", carInformation.getId(),
                    "PhyDepotList", shippingAddressList,
                    "waybillList", maps,
                    "type","签收确认"
            ));
        });
        return cacheList;
    }


    /**
     * 查询已完成的派车单
     * @param request
     * @return
     */
    public List findCarInformationByChauffeurAndStatus(SimpleRequest request){
        Map m = request.getMap();
        String phone = (String) m.get("phone");
        String dateString = (String) m.get("date");
        Chauffeur chauffeur = chauffeurRepository.findByMobileNumber(phone);
        // 查询所有该司机已完成的派车单
        List<CarInformation> carInformationList = carInformationRepository.findAllByChauffeurIdAndStatus(chauffeur,"done");
        if (dateString!=null ){
            Date date = DateUtil.parse(dateString,"yyyy-MM");
            LocalDate localDate = DateUtil.UDateToLocalDate(date);
            LocalDate first = localDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate last = localDate.with(TemporalAdjusters.lastDayOfMonth());
            carInformationList = carInformationList.stream()
                    .filter(c -> DateUtil.dateToDate(c.getLastUpdatedStamp(),"yyyy-MM-dd").getTime()>= DateUtil.ULocalDateToDate(first).getTime()
                            && DateUtil.dateToDate(c.getLastUpdatedStamp(),"yyyy-MM-dd").getTime() <= DateUtil.ULocalDateToDate(last).getTime())
                    .collect(Collectors.toList());
        }
        List<Map> maps = new ArrayList<>();

        carInformationList.forEach(carInformation -> {
            Map map = MapUtil.mapper(
                    "id", carInformation.getId(),
                    "vehicleId", carInformation.getVehicleId(),
                    "status", carInformation.getStatus(),
                    "branchLineId", carInformation.getBranchLineId(),
                    "chauffeurId", carInformation.getChauffeurId(),
                    "lastUpdatedStamp", carInformation.getLastUpdatedStamp()
            );
            maps.add(map);
        });
        return maps;
    }


    /**
     * 查询派车单里的运单列表
     * @param request
     * @return
     */
    public List findWaybillByCarInformationAndStatus(SimpleRequest request){
        Map m = request.getMap();
        String carInformationId = (String) m.get("carInformationId");
        CarInformation carInformation = carInformationRepository.findOne(carInformationId);
        // 此次派车单 所有运单 经过的仓库
        List<CarDetails> carDetailsList = carDetailsRepository.findAllByCarInformationId(carInformation);
        List<Waybill> waybillList = carDetailsList.stream().map(CarDetails::getWaybillId).collect(Collectors.toList());
        // 此次派车单 所有 已签收 已中转暂存的运单
        List<Map> maps = new ArrayList<>();

        waybillList.forEach(waybill -> {
            Map map = MapUtil.mapper(
                    "id",waybill.getId(),
                    "sourceBusinessType",waybill.getSourceBusinessType(),
                    "sourceBusinessKey",waybill.getSourceBusinessKey(),
                    "transportStatus",waybill.getTransportStatus(),
                    "deliveryAddress",waybill.getDeliveryAddress(),
                    "shippingAddress",waybill.getShippingAddress()
            );
            maps.add(map);
        });

        return maps;
    }

    /**
     * 获取运单来源单的
     * 出库单列表
     * @param request
     * @return
     */
    public List getOutbound(SimpleRequest request){
        Map m = request.getMap();
        String waybillId = (String) m.get("waybillId");
        Waybill waybill = waybillRepository.findOne(waybillId);
        List<Map> cacheList = new ArrayList();
        // 来自新框架的 运单
        if ("Pick".equals(waybill.getSourceBusinessType())){
            Pick pick = pickRepository.findOne(waybill.getSourceBusinessKey());
            Map map = MapUtil.mapper(
                    "id", pick.getId(),
                    "object", pick
            );
            cacheList.add(map);
        } else if ("PurchaseOrder".equals(waybill.getSourceBusinessType())){
            Map map = MapUtil.mapper(
                    "id", waybill.getId(),
                    "object", waybill
            );
            cacheList.add(map);
        } else { // 来自旧框架的运单
            // 调接口取旧框架的商品列表
            JSONObject ZCDD = new JSONObject();
            ZCDD.put("DJHM", waybill.getSourceBusinessKey());
            JSONObject category = piManager.synErp("scmZcddService.qryZCDDMXInfo", ZCDD);
            String obj = category.getString("obj");
            JSONArray rows = JSONArray.parseArray(obj);
            if (rows.isEmpty()) throw new RuntimeException("没有对应的出库单.");
            Map<String, List<Object>> rowMaps = rows.stream().collect(Collectors.groupingBy(json -> {
                JSONObject jsonObject = (JSONObject) json;
                String CKDH = jsonObject.getString("CKDH");
                if (CKDH == null) throw new RuntimeException("没有对应的出库单.");
                return CKDH;
            }));
            rowMaps.forEach((k, v) -> {
                Map map = MapUtil.mapper(
                        "id", k,
                        "object", v
                );
                cacheList.add(map);
            });
        }

        return cacheList;
    }


    /**
     * 获取运单来源单的
     * 入库单列表
     * @param request
     * @return
     */
    public List getPickList(SimpleRequest request){
        Map m = request.getMap();
        String waybillId = (String) m.get("waybillId");
        Waybill waybill = waybillRepository.findOne(waybillId);
        List<Map> cacheList = new ArrayList();
        // 来自新框架的 运单
        if ("Pick".equals(waybill.getSourceBusinessType())){
            Pick pick = pickRepository.findOne(waybill.getSourceBusinessKey());
            List<Pick> pickList = pickRepository.findByOriginAndOperation(pick.getOrigin(),"receipt");
            pickList.forEach(pick1 -> {
                Map map = MapUtil.mapper(
                        "id", pick1.getId(),
                        "object", pick1
                );
                cacheList.add(map);
            });

        } else if ("PurchaseOrder".equals(waybill.getSourceBusinessType())){
            Map map = MapUtil.mapper(
                    "id", waybill.getId(),
                    "object", waybill
            );
            cacheList.add(map);
        } else { // 来自旧框架的运单
            // 调接口取旧框架的商品列表
            JSONObject ZCDD = new JSONObject();
            ZCDD.put("DJHM", waybill.getSourceBusinessKey());
            JSONObject category = piManager.synErp("scmZcddService.qryZCDDMXInfo", ZCDD);
            String obj = category.getString("obj");
            JSONArray rows = JSONArray.parseArray(obj);
            if (rows.isEmpty()) throw new RuntimeException("没有对应的入库单.");
            Map<String, List<Object>> rowMaps = rows.stream()
                    .filter(objs -> {
                        JSONObject jsonObject = (JSONObject)objs;
                        return jsonObject.getString("CKDH").equals(waybill.getOutboundOrder());
                    })
                    .collect(Collectors.groupingBy(json -> {
                JSONObject jsonObject = (JSONObject) json;
                String RKDH = jsonObject.getString("RKDH");
                if (RKDH ==null)throw new RuntimeException("没有对应的入库单.");
                return RKDH;
            }));
            rowMaps.forEach((k, v) -> {
                Map map = MapUtil.mapper(
                        "id", k,
                        "object", v
                );
                cacheList.add(map);
            });
        }

        return cacheList;
    }


    /**
     * 装货确认
     * @param request
     */
    public boolean loaded(SimpleRequest request){
        Map m = request.getMap();
        String waybillId = (String) m.get("waybillId");
        WaybillPlanningPlan waybillPlanningPlan = request.getO("waybillPlanningPlan",WaybillPlanningPlan.class);
        // 出库单信息
        Object object = m.get("sourceBusinessKey");

//        Object object = m.get("object");
        Waybill waybill = waybillRepository.findOne(waybillId);
        AtomicBoolean returnStatus = new AtomicBoolean(false);
        StringBuffer string = new StringBuffer();
        // 根据来源单据号 和 来源单据类型 查询出运单 判断运单明细的商品 与 交货单的商品是否对应
        List<WaybillCargoDetails> waybillCargoDetailsSet = waybill.getWaybillCargoDetailsSet();
        // 创建新运单的商品列表
        JSONArray ITEM_Array = new JSONArray();
        if("Pick".equals(waybill.getSourceBusinessType())){
//            JSONObject json = JSON.parseObject(object.toString());
//            String SPID = json.getString("SPID");
            // 如果是根据交货单生成的运单 判断对比交货单的商品明细数量
            Pick pick = pickRepository.findOne(waybill.getSourceBusinessKey());
            if(!pick.getOriginBusinessType().equals("PurchaseOrder")){
                if (!"done".equals(pick.getState())) throw new RuntimeException("请先发货,才能装货.");
                Set<PickItem> pickItemSet = pick.getPickItems();
                // 判断运单里的商品数量 与交货数量是否对应
                waybillCargoDetailsSet.stream().forEach(waybillCargoDetails -> {
                    PickItem pickItem1 = pickItemSet.stream().filter(pickItem -> pickItem.getProduct() == waybillCargoDetails.getProductId()).findFirst().orElse(null);
                    if (pickItem1.getQtyDone() != waybillCargoDetails.getLoadingQty()) {
                        returnStatus.set(true);
                        string.append(pickItem1.getProduct().getName() +"  " + waybillCargoDetails.getLoadingQty() + "/" +
                                pickItem1.getQtyDone() +" " + waybillCargoDetails.getProductUomId().getName()+"\n");
                    }
                });
            }

            waybill.setOutboundOrder(pick.getId());
        } else if ("PurchaseOrder".equals(waybill.getSourceBusinessType())){
            waybill.setOutboundOrder(waybillId);
        } else {
            /*
            来自旧框架的转储/调拨单，生成的出库单，如果是分批出库。根据此次出库的商品和数量比较后。
            剩余的商品及数量生成新的运单，直至剩余的商品及数量为0
             */
            AtomicBoolean status = new AtomicBoolean(false);

            JSONArray jsonArray = JSON.parseArray(object.toString());

            waybillCargoDetailsSet.stream().forEach(waybillCargoDetails -> {
               Object productObject = jsonArray.stream().filter(obj -> {
                    JSONObject jsonObject = (JSONObject)obj;
                    if (!(jsonObject.getString("CKDJZT").equals("10") || jsonObject.getString("CKDJZT").equals("20")))throw new RuntimeException("请先发货,才能装货.");
                    return jsonObject.getString("SPID").equals(waybillCargoDetails.getProductId().getId());
                }).findFirst().orElse(null);

                /*
                 如果选择的出库单里没有此次运单的商品 生成新的运单 商品列表是不在此次运单里的商品
                 如果在此次运单商品列表里 但是出库的数量与运单的数量不对等时，加入新运单的商品列表商品数量为订单数量-出库数量
                 */
               if(productObject == null){
                   waybillCargoDetails.setLoadingQty(0);
//                   status.set(true);
//                   JSONObject item = new JSONObject();
//                   item.put("SPID",waybillCargoDetails.getProductId().getId());
//                   item.put("SPMC",waybillCargoDetails.getProductId().getName());
//                   item.put("JLDWID",waybillCargoDetails.getProductUomId().getId());
//                   item.put("JLDW",waybillCargoDetails.getProductUomId().getName());
//                   item.put("ZCSL",waybillCargoDetails.getLoadingQty());
//                   ITEM_Array.add(item);
               } else {
                   JSONObject jsonObject = (JSONObject)productObject;
                   String SPID = jsonObject.getString("SPID");
                   String CKDH = jsonObject.getString("CKDH");
                   int FHSL = jsonObject.getIntValue("FHSL");
                   if(FHSL != waybillCargoDetails.getLoadingQty()){

                       waybillCargoDetails.setLoadingQty(FHSL);
//                       status.set(true);
//                       JSONObject item = new JSONObject();
//                       item.put("SPID",jsonObject.get("SPID"));
//                       item.put("SPMC",jsonObject.get("SPMC"));
//                       item.put("JLDWID",jsonObject.get("JLDWID"));
//                       item.put("JLDW",jsonObject.get("JLDW"));
//                       item.put("ZCSL",jsonObject.getIntValue("ZCSL") - FHSL);
//                       ITEM_Array.add(item);
                   }
                   waybill.setOutboundOrder(CKDH);
               }

            });
            // 生成新运单
//            if (status.get()){
//                JSONObject newObject = new JSONObject();
//                newObject.put("DJLXID",waybill.getSourceBusinessType());
//                newObject.put("LYDJLXID",waybill.getSourceBusinessType());
//                newObject.put("DH",waybill.getSourceBusinessKey());
//                newObject.put("FHCKID", waybill.getDeliveryAddress().getId());
//                newObject.put("FHCKMC", waybill.getDeliveryAddress().getName());
//                newObject.put("SHCKID", waybill.getShippingAddress().getId());
//                newObject.put("SHCKMC", waybill.getShippingAddress().getName());
//
//                newObject.put("ITEM",ITEM_Array);
//                SimpleRequest request1 = new SimpleRequest();
//                request1.setData(newObject);
//                waybillService.create(request1);
//            }

        }
        if (returnStatus.get()){
            throw new RuntimeException(string.toString());
        }

        CarDetails carDetails = carDetailsRepository.findAllByWaybillIdAndCarInformationId(waybill,waybillPlanningPlan.getCarInformationId());

        waybill.setTransportStatus("inTransit");
        waybillPlanningPlan.setStatus("inTransit");
        waybillPlanningPlan.setLoadingTime(new Date());
        waybillPlanningPlanRepository.saveAndFlush(waybillPlanningPlan);

        WaybillPlanningLog waybillPlanningLog = new WaybillPlanningLog();
//            waybillPlanningLog.setWaybillId(waybill);
//            waybillPlanningLog.setNotes("货物已指派给" + chauffeur.getName()+",派车单"+ carInformation.getId() + "已生成！");
//            waybillPlanningLogRepository.save(waybillPlanningLog);
//
//            waybillPlanningLog = new WaybillPlanningLog();
        waybillPlanningLog.setWaybillId(waybill);
        waybillPlanningLog.setCarDetailsId(carDetails);
        String transportStatus = waybill.getTransportStatus();
        transportStatus = transportStatus.equals("collection")?"待揽收":transportStatus.equals("sendCar")?"待派车":transportStatus.equals("loading")?"待装车":
                transportStatus.equals("inTransit")?"运输中":transportStatus.equals("received")?"已签收":transportStatus.equals("temporary")?"暂存中转站":"";
        waybillPlanningLog.setNotes("【" + phyDepotRepository.findOne(waybill.getShippingAddress().getId()).getName() + "】运单" + transportStatus);
        waybillPlanningLogRepository.save(waybillPlanningLog);

        // 如果是运单的第一条的线路规划装货 将装货时间添加上
        if (waybillPlanningPlan.getExecutionNumber() == 1){
            waybill.setLoadingTime(new Date());
        }
        Waybill waybill1 = waybillRepository.saveAndFlush(waybill);
        this.qryWaybillLoadingOrSignFor(waybill, "loading", waybillPlanningPlan);
        return true;

    }


    /**
     * 签收确认
     * 从 转储入库单（新旧系统） 采购订单
     * 交货单
     * @param request
     */
    public boolean signFor(SimpleRequest request){
        Map m = request.getMap();
        WaybillPlanningPlan waybillPlanningPlan = request.getO("waybillPlanningPlan",WaybillPlanningPlan.class);
        String waybillId = (String) m.get("waybillId");
        // 入库单信息
        Object object = m.get("sourceBusinessKey");

        Waybill waybill = waybillRepository.findOne(waybillId);
        AtomicBoolean returnStatus = new AtomicBoolean(false);
        StringBuffer string = new StringBuffer();
        // 根据来源单据号 和 来源单据类型 查询出运单 判断运单明细的商品 与 交货单的商品是否对应
        List<WaybillCargoDetails> waybillCargoDetailsSet = waybill.getWaybillCargoDetailsSet();

        if("Pick".equals(waybill.getSourceBusinessType())){
//           Pick pick = jsonArray.getObject(0,Pick.class);
            // 如果是根据交货单生成的运单 判断对比交货单的商品明细数量
            Pick pick = request.getO("sourceBusinessKey",Pick.class);
            if(!pick.getOriginBusinessType().equals("PurchaseOrder")){
                if (!"done".equals(pick.getState())) throw new RuntimeException("请先入库,才能签收.");
                Set<PickItem> pickItemSet = pick.getPickItems();
                // 判断运单里的商品数量 与交货数量是否对应
                waybillCargoDetailsSet.stream().forEach(waybillCargoDetails -> {
                    PickItem pickItem1 = pickItemSet.stream().filter(pickItem -> pickItem.getProduct() == waybillCargoDetails.getProductId()).findFirst().orElse(null);
                    if (pickItem1.getQtyDone() != waybillCargoDetails.getLoadingQty()) {
                        returnStatus.set(true);
                        string.append(pickItem1.getProduct().getName() +"  " + waybillCargoDetails.getLoadingQty() + "/" +
                                pickItem1.getQtyDone() +" " + waybillCargoDetails.getProductUomId().getName()+ "\n");
                    }
                });
            }

            waybill.setReceiptOrder(pick.getId());
        }else if ("PurchaseOrder".equals(waybill.getSourceBusinessType())){
            waybill.setReceiptOrder(waybillId);
        }  else {
            /*
            来自旧框架的转储/调拨单，生成的出库单，如果是分批出库。根据此次出库的商品和数量比较后。
            剩余的商品及数量生成新的运单，直至剩余的商品及数量为0
             */
            JSONArray jsonArray = JSON.parseArray(object.toString());
            if ("ZD2".equals(waybill.getSourceBusinessType())){

                String RKDH = jsonArray.getJSONObject(0).getString("RKDH");
                Pick pick = pickRepository.findOne(RKDH);
                if (!"done".equals(pick.getState())) throw new RuntimeException("请先入库,才能签收.");
                waybill.setReceiptOrder(pick.getId());
            } else {
                waybillCargoDetailsSet.stream().forEach(waybillCargoDetails -> {
                    Object productObject = jsonArray.stream().filter(obj -> {
                        JSONObject jsonObject = (JSONObject)obj;
                        if (!jsonObject.getString("RKDJZT").equals("10"))throw new RuntimeException("请先入库,才能签收.");
                        return jsonObject.getString("SPID").equals(waybillCargoDetails.getProductId().getId());
                    }).findFirst().orElse(null);

                    if (waybillCargoDetails.getLoadingQty()!=0){
                        if (productObject == null ){
                            throw new RuntimeException("选择的入库单与运单的商品种类不对应。");
                        }
                        JSONObject jsonObject = (JSONObject)productObject;
                        String SPMC = jsonObject.getString("SPMC");
                        String RKDH = jsonObject.getString("RKDH");
                        int FHSL = jsonObject.getIntValue("FHSL");
                        if(FHSL != waybillCargoDetails.getLoadingQty()){
                            returnStatus.set(true);
                            string.append(SPMC + "  " + waybillCargoDetails.getLoadingQty() + "/" +
                                    FHSL + " " + waybillCargoDetails.getProductUomId().getName()+ "\n");
                        }
                        waybill.setReceiptOrder(RKDH);
                    }

                });
            }



        }
        if (returnStatus.get()){
            throw new RuntimeException(string.toString());
        }

        // 根据来源单据号 和 来源单据类型 查询出运单 判断运单明细的商品 与 交货单的商品是否对应
        CarDetails carDetails = carDetailsRepository.findAllByWaybillIdAndCarInformationId(waybill,waybillPlanningPlan.getCarInformationId());
        waybill.setTransportStatus("received");
        waybill.setReceivedDate(new Date());
        waybillPlanningPlan.setStatus("arrived");
        waybillPlanningPlanRepository.saveAndFlush(waybillPlanningPlan);

        WaybillPlanningLog waybillPlanningLog = new WaybillPlanningLog();

        waybillPlanningLog.setWaybillId(waybill);
        waybillPlanningLog.setCarDetailsId(carDetails);
        String transportStatus = waybill.getTransportStatus();
        transportStatus = transportStatus.equals("collection")?"待揽收":transportStatus.equals("sendCar")?"待派车":transportStatus.equals("loading")?"待装车":
                transportStatus.equals("inTransit")?"运输中":transportStatus.equals("received")?"已签收":transportStatus.equals("temporary")?"暂存中转站":"";
        waybillPlanningLog.setNotes("【" + phyDepotRepository.findOne(waybill.getShippingAddress().getId()).getName() + "】运单" + transportStatus);
        waybillPlanningLogRepository.save(waybillPlanningLog);

        //判断该派车单下的所有运单是否都 已签收 当全部签收时回写派车单状态
        CarInformation carInformation = carDetails.getCarInformationId();
        List<WaybillPlanningPlan> waybillPlanningPlanList = waybillPlanningPlanRepository.findByCarInformationId(carInformation).stream()
                .filter(waybillPlanningPlan1 -> !waybillPlanningPlan1.getStatus().equals("arrived")).collect(Collectors.toList());
//        List<CarDetails> carDetailsList = carDetailsRepository.findAllByCarInformationId(carInformation );
        if (waybillPlanningPlanList.isEmpty()){
            carInformation.setStatus("done");
        }
        this.qryWaybillLoadingOrSignFor(waybill, "signFor", waybillPlanningPlan);
        return true;
    }

    /**
     * 装车
     * @param waybill1
     */
    private void qryWaybillLoadingOrSignFor(Waybill waybill1, String djlxid, WaybillPlanningPlan waybillPlanningPlan) {
        PurchaseOrder purchaseOrder = SpringManager.getBean(PurchaseOrderRepository.class).findOne(waybill1.getSourceBusinessKey());
        if (!"CD0".equals(purchaseOrder.getSourceType())) return;
        JSONObject param = new JSONObject();
        param.put("SYID", purchaseOrder.getProductRequire());
        param.put("XYID", waybill1.getId());
        param.put("DJLXID", djlxid);
        param.put("RYMC", waybillPlanningPlan.getCarInformationId().getChauffeurId().getName());
        param.put("PHONE", waybillPlanningPlan.getCarInformationId().getChauffeurId().getMobileNumber());
        try {
            param.put("ZXRQ_SJ", com.apestech.framework.json.JSON.toJSONStringWithDateFormat(new Date()));
        } catch (Exception e) {
            throw new RuntimeException("日期转换失败" + param);
        }
        JSONArray itemArray = new JSONArray();
        waybill1.getWaybillCargoDetailsSet().stream().filter(waybillCargoDetails -> waybillCargoDetails.getLoadingQty() > 0).forEach(waybillCargoDetails -> {
            JSONObject item = new JSONObject();
            item.put("SPID", waybillCargoDetails.getProductId().getId());
            item.put("SL", waybillCargoDetails.getLoadingQty());
            item.put("JLDW", waybillCargoDetails.getProductUomId().getName());
            itemArray.add(item);
        });
        param.put("item", itemArray);

        SpringManager.getBean(OutboxSubscriberService.class).commonSendRequest("local:WaybillService.insertWaybillWLGZ", "waybillSignFor_waybillId" + waybill1.getId(), param);
    }

}
